<?php
/**

 //  DoYouHaoBaby-X Ucenter ( DoYouHaoBaby-X 计划 )
 //  +---------------------------------------------------------------------
 //
 //  “Copyright”
 //  +---------------------------------------------------------------------
 //	 | (C) 2010 - 2011 http://doyouhaobaby.net All rights reserved.
 //	 | This is not a free software, use is subject to license terms
 //  +---------------------------------------------------------------------
 //
 //  “About This File”
 //  +---------------------------------------------------------------------
 //	 | Ucenter 应用模型
 //  +---------------------------------------------------------------------

*/

!defined( 'DYHB_PATH' ) && exit;

class ApplicationModel extends CommonModel{

    /**
     * 返回对象的定义
     */
    static public function init__(){

        return array(

            'table_name' => 'application',

            'check' => array(

                'application_name'=>array(

                    array( 'require',G::L( '应用名不能为空!' ) ),
                ),

                'application_url'=>array(

                    array( 'require',G::L( '应用地址不能为空!' ) ),
                    array( 'url2',G::L( '应用地址格式错误!' ) ),
                ),
            ),

	        'autofill' => array(

    	        array('application_authkey','authkeyAuthcode','CREATE','callback'),
    	        array('application_tagtemplates','tagTemplates','ALL','callback'),
    	        array('application_extra','extra','ALL','callback'),
             ),
        );
    }

    /**
     * 开启一个查询，查找符合条件的对象或对象集合
     */
    static function F(){

        $arrArgs = func_get_args();
        return ModelMeta::instance( __CLASS__ )->findByArgs( $arrArgs );
    }

    /**
     * 返回当前 Model 类的元数据对象
     */
    static function M(){

        return ModelMeta::instance( __CLASS__ );
    }

    /**
     * application_authkey字段 回调加密
     */
    protected function authkeyAuthcode( ){

        return E::authcode( Safe::getGpc( 'application_authkey' ), 'ENCODE' );
    }

    /**
     * application_tagtemplate字段 回调
     */
    protected function tagTemplates( ){

	    $arrTagTemplates = array( );
		$arrTagTemplates['template'] = Input::addslashes(  trim(  Safe::getGpc( 'application_tagtemplates' ) ) );

		$arrTagFields = explode( "\n", trim( trim(  Safe::getGpc( 'tagfields' ) ) ) );
		foreach( $arrTagFields as $sField ) {

			$sField = trim( $sField );
			$arrField = explode( ',', $sField );
			if( !empty( $arrField[0] ) ) {

				$arrTagTemplates['fields'][ $arrField[0] ] = !empty( $arrField[1] ) ? $arrField[1] :'';
			}
		}
		
		return Xml::xmlSerialize( $arrTagTemplates, true );
	}

	/**
     * application_extra字段 回调
     */
	protected function extra( ){

		$arrExtra = array();

		$sApppath = Safe::getGpc( 'apppath' );
		$arrExtra[ 'apppath' ] = $this->realpath( $sApppath );

	    if( $sApppath ) {

			 $arrExtra[ 'apppath' ] = $this->realpath( $sApppath );
			 if( $arrExtra['apppath'] ) {

				  $sApifile = G::tidyPath( $arrExtra['apppath'].'./Api/Uc.php' );

				  if( !is_file( $sApifile ) ) {

					  $this->setErrorMessage( G::L( 'API文件%s不存在！','app',null,$sApifile ) );
					  return '';
				  }

				  $sContent = file_get_contents( $sApifile );

				  preg_match("/define\(\'UC_CLIENT_VERSION\'\,\'([^\']+?)\'\)/i", $sContent, $arrM );

				  $nUcClientVersion = !empty( $arrM[1] ) ? $arrM[1]:'' ;

			      // 判断版本
				  if( !$nUcClientVersion || $nUcClientVersion <= '1.0.0' ) {

				      $this->setErrorMessage( G::L( 'API文件%s版本太低！','app',null,$sApifile ) );
					  return '';
				  }

			   }

			   else {

				   $this->setErrorMessage( G::L( 'API文件%s不存在！','app',null,$arrExtra['apppath'] ) );
				   return '';
			   }

		}

		else {

			$arrExtra['apppath'] = '';
		}

		$arrExtra = serialize( Input::addslashes(  $arrExtra ) );
		return $arrExtra;
	}

	/**
	 * realpath 路径
	 */
	protected function realpath( $sPath ) {

		return realpath( $sPath ).'/';
	}

	/**
	 * 取得App 数据
	 */
	public function getAppByAppid( $nAppId, $bIncludeCert = FALSE ) {

		$nAppId = intval( $nAppId );
		$arrValue = self::F( 'application_id=?',$nAppId )
		            ->query()
		            ->toArray();

		$arrValue['application_extra'] = trim( $arrValue['application_extra'] )!=''?unserialize( $arrValue['application_extra'] ):'';
		if( $sTmp = E::authcode( $arrValue['application_authkey'], 'DECODE', UC_MYKEY ) ) {

			$arrValue['application_authkey'] = $sTmp;
		}

		return $arrValue;
	}

	/**
	 * 测试Api
	 */
	public function testApi( $sUrl, $sIp = '' ) {

		if( !$sIp ) {

			$sIp = $this->getHostByUrl( $sUrl );
		}

		if( $sIp < 0 ) {

			return FALSE;
		}

		return $this->fopen( $sUrl, 0, '', '', 1, $sIp );
	}

}
